from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=50)
    author = models.CharField(max_length=20)

    #查询1
    def get_all():
        books = Book.objects.all()
        data = [{'id': book.id, 'title': book.title, 'author': book.author} for book in books]
        return data

    #查询2
    def get_book(book_id):
        try:
            book = Book.objects.get(id=book_id)
            data = {'id': book.id, 'title': book.title, 'author': book.author}
            return data
        except Book.DoesNotExist:
            return None

    #增
    def create_book(title, author):
        try:
            Book.objects.create(title=title, author=author)
            return True
        except:
            return False

    #删
    def delete_book(book_title):
        try:
            book = Book.objects.get(title=book_title)
            book.delete()
            return True
        except Book.DoesNotExist:
            return False

    #改
    def update_book(book_id, title=None, author=None):
        try:
            book = Book.objects.get(pk=book_id)
            if title:
                book.title = title
            if author:
                book.author = author
            book.save()
            return True
        except Book.DoesNotExist:
            return False
